package com.jiangyg.mall.redis;

import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.config.ConfigService;
import com.jiangyg.mall.core.utils.Logger;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.spring.starter.RedissonAutoConfiguration;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * 类描述：Redission自动配置（主要用于分布式锁）
 * <p>覆盖 {@link RedissonAutoConfiguration org.redisson.spring.starter.RedissonAutoConfiguration} 配置类的 RedissonClient 配置。</p>
 * <p>初始化 RedissonClient 客户端，配置文件从 nacos 配置中心获取。</p>
 *
 * @author jiangyg
 * @date 2021-12-08
 */
@Slf4j
@ConditionalOnClass({Redisson.class})
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(name = "spring.redisson.nacos.enabled", havingValue = "true")
@AutoConfigureBefore({RedisAutoConfiguration.class, RedissonAutoConfiguration.class})
public class RedissionNacosAutoConfiguration implements InitializingBean {

    @Value("${spring.redisson.nacos.data-id}")
    private String dataId;

    @Value("${spring.redisson.nacos.group:" + Constants.DEFAULT_GROUP + "}")
    private String group;

    private NacosConfigManager nacosConfigManager;

    @Autowired
    public RedissionNacosAutoConfiguration(NacosConfigManager nacosConfigManager) {
        this.nacosConfigManager = nacosConfigManager;
    }

    /**
     * 功能描述：Redisson操作的客户端
     *
     * @return 客户端
     */
    @Bean(destroyMethod = "shutdown")
    public RedissonClient redissonClient() throws Exception {
        final ConfigService configService = nacosConfigManager.getConfigService();
        final String configString = configService.getConfig(dataId, group, 10000);
        final Config config = Config.fromYAML(configString);
        return Redisson.create(config);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Logger.info(log, () -> "[项目启动]-初始化Redisson缓存配置……");
    }

}
